package org.zzz.hepotaiya.callable;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.Callable;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.zzz.hepotaiya.beans.BatchInfo;
import org.zzz.hepotaiya.enums.ResultType;
import org.zzz.hepotaiya.util.ResourceUtil;

/**
 * 非同期実行クラス
 */
public class CallableImpl implements Callable<BatchInfo> {

	private static final Logger logger = Logger.getLogger(CallableImpl.class);

	String skipCause;
	
	/**
	 * 
	 * @param skipCause
	 */
	public void setSkipCause(String skipCause) {
		this.skipCause = skipCause;
	}

	BatchInfo batchInfo;

	/**
	 * 
	 * @param batchInfo
	 */
	public void setBatchInfo(BatchInfo batchInfo) {
		this.batchInfo = batchInfo;
	}

	/**
	 * 非同期実行
	 * 
	 * @see java.util.concurrent.Callable#call()
	 */
	public BatchInfo call() {
		try {
			// 依存チェック
			if (!StringUtils.isEmpty(this.skipCause)) {
				logger.warn(ResourceUtil.getString("callable.log.skip", batchInfo.getBatchName(),this.skipCause));
				batchInfo.setResultType(ResultType.SKIP);
				return batchInfo;
			}
			// 実行
			batchInfo.setReturnObject(batchInfo.getTargetMethod().invoke(batchInfo.getTargetObject()));
			// 結果格納
			batchInfo.dispatchResultType(batchInfo.getTargetMethod().getReturnType(), batchInfo.getReturnObject());
			return batchInfo;
		} catch(InvocationTargetException ite) {
			batchInfo.setResultType(ResultType.FAILURE);
			logger.error(batchInfo.getBatchName() +":"+ite);
		} catch (Exception ex) {
			batchInfo.setResultType(ResultType.FAILURE);
			logger.error(batchInfo.getBatchName()+":"+ex);
		}
		return batchInfo;
	}
}
